package ddz;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kaka.Startup;
import com.kaka.notice.Facade;
import com.kaka.notice.FacadeFactory;
import com.kaka.util.Charsets;
import com.kaka.util.ResourceUtils;
import ddz.numerical.ConfManager;
import ddz.utils.JsonUtils;
import ddz.utils.Zlib;

import java.io.*;
import java.util.List;

public class MergeConfig extends Startup {

    public static void main(String[] args) throws Exception {
        MergeConfig main = new MergeConfig();
        main.scan("ddz.numerical.manager");
        String path = ResourceUtils.getClassLoaderPath(MergeConfig.class);
        File dir = new File(path + "/usr-config");
        File[] files = dir.listFiles();
        Facade facade = FacadeFactory.getFacade();

        ObjectNode jsonObject = JsonUtils.createJsonObject();

        for (File file : files) {
            try (InputStream is = new FileInputStream(file)) {
                ConfManager manager = facade.retrieveProxy(file.getName());
                if(manager != null) {
                    manager.parse(is, "UTF-8", 1);
                    List list = manager.getList();
                    String name = file.getName();
                    int idx = name.indexOf(".txt");
                    if (idx > 0) {
                        name = name.substring(0, idx);
                    }
                    ArrayNode jsonArray = jsonObject.putArray(name);
                    list.forEach((Object obj) -> {
                        jsonArray.addPOJO(obj);
                    });
                    System.out.println("配置文件解析完成：" + file.getName());
                }
            }
        }

        String json = JsonUtils.toJsonString(jsonObject);
        byte[] bytes = json.getBytes(Charsets.utf8);
        bytes = Zlib.compress(bytes);
        saveFile(bytes, "d:/", "usr-config.bytes");
        System.out.println(json);
    }

    private static void saveFile(byte[] content, String dicPath, String fileName) throws IOException {
        File targetFile = new File(dicPath + "/" + fileName);
        if (!targetFile.exists()) targetFile.createNewFile();
        if (!targetFile.canWrite()) return;
        try (FileOutputStream fos = new FileOutputStream(targetFile)) {
            fos.write(content);
            fos.flush();
        }
    }

}
